//
//  CommonViewController.m
//  MeterMart
//
//  Created by ENERGY on 2018/10/25.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "CommonViewController.h"
#import <WebKit/WebKit.h>
#import "CartViewController.h"
#import "MineViewController.h"
@interface CommonViewController ()<WKNavigationDelegate>
@property (nonatomic, strong)WKWebView * webView;
@property (nonatomic, assign)int webH;//web页的高度
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UIViewController * lastVC;//push过来的控制器

@end

@implementation CommonViewController(networking)

- (void)getURLData{
    NSDictionary * dic = @{
                         @"newsid":self.pageType
                         };
    [self showprogressHUD];
    [[AFAppDotNetAPIClient sharedClient] POST:@"teamApi/newsinfo" parameters:dic progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self hiddenProgressHUD];
        if ([responseObject[@"sign"] isEqualToString:@"1"]) {
            [self.webView loadHTMLString:responseObject[@"list"][@"content"] baseURL:nil];
        }else{
            ShowMessage(responseObject[@"msg"]);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [self hiddenProgressHUD];
        [self showError:error];
    }];
}
@end
@implementation CommonViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    [self getURLData];//数据接口
    [self.view addSubview:self.tableView];
    
    NSArray *vcsArray = [self.navigationController viewControllers];
    NSInteger vcCount = vcsArray.count;
    self.lastVC = vcsArray[vcCount-1];
    if ([self.lastVC isKindOfClass:[MineViewController class]]) {
        
    }else{
        if (vcsArray.count>1){
            
        }else{
            [self setUpNavigationItem];
        }
    }
}
- (void)setUpNavigationItem{
    //左侧按钮
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 30/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [backBtn setImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT - BOTTOM_HEIGHT - NAVI_HEIGHT) style:UITableViewStylePlain];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        _tableView.tableHeaderView = self.headerView;
    }return _tableView;
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 100)];
        _headerView.backgroundColor= [UIColor clearColor];
        //        首先是关键JS代码：
        NSString *jScript =
        @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta); var imgs = document.getElementsByTagName('img');for (var i in imgs){imgs[i].style.maxWidth='100%';imgs[i].style.height='auto';}";
        //        然后初始化并加入JS片段：
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        WKWebViewConfiguration *wkWebConfig = [[WKWebViewConfiguration alloc] init];
        wkWebConfig.userContentController = wkUController;
        self.webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 0) configuration:wkWebConfig];
        self.webView.scrollView.bounces = NO;
        self.webView.scrollView.showsHorizontalScrollIndicator = NO;
        self.webView.scrollView.scrollEnabled = NO;
        self.webView.navigationDelegate = self;
        [_headerView addSubview:self.webView];
    }return _headerView;
}
#pragma mark - WKWebViewDelegeta
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    WS(ws)
    [webView evaluateJavaScript:@"document.body.offsetHeight;" completionHandler:^(id _Nullable any, NSError * _Nullable error) {
        NSString *heightStr = [NSString stringWithFormat:@"%@",any];
        ws.webH = [heightStr intValue];
        self.headerView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.webH + 20/WIDTH_6_SCALE);
        self.webView.frame = CGRectMake(0, 0, SCREEN_WIDTH, self.headerView.bottom);
        self.tableView.tableHeaderView = self.headerView;
        [self.tableView reloadData];
    }];
}
#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
    [self dismissViewControllerAnimated:YES completion:nil];
}
@end
